package com.example.springboot.controller;


import com.example.springboot.entity.Question;
import com.example.springboot.entity.Res;
import com.example.springboot.service.Impl.QuestionServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/questions")
public class QuestionController {

    @Autowired
    private QuestionServiceImpl questionService;

    @PostMapping
    public Res<Void> addQuestion(@RequestBody Question question) {
        try {
            questionService.addQuestion(question);
            return new Res<Void>().code(200).msg("问题添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Res<Void>().code(500).msg("服务错误");
        }
    }

    @GetMapping("/{id}")
    public Res<Question> getQuestionById(@PathVariable int id) {
        try {
            Question question = questionService.getQuestionById(id);
            if (question != null) {
                return new Res<Question>().code(200).msg("查询成功").data(question);
            } else {
                return new Res<Question>().code(404).msg("问题未找到");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Res<Question>().code(500).msg("服务错误");
        }
    }

    @GetMapping("/post/{postId}")
    public Res<List<Question>> getQuestionsByPostId(@PathVariable int postId) {
        try {
            List<Question> questions = questionService.getQuestionsByPostId(postId);
            return new Res<List<Question>>().code(200).msg("查询成功").data(questions);
        } catch (Exception e) {
            e.printStackTrace();
            return new Res<List<Question>>().code(500).msg("服务错误");
        }
    }

    @PutMapping("/{id}")
    public Res<Void> updateQuestion(@PathVariable int id, @RequestBody Question question) {
        try {
            question.setId(id);
            questionService.updateQuestion(question);
            return new Res<Void>().code(200).msg("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Res<Void>().code(500).msg("服务错误");
        }
    }

    @DeleteMapping("/{id}")
    public Res<Void> deleteQuestion(@PathVariable int id) {
        try {
            questionService.deleteQuestion(id);
            return new Res<Void>().code(200).msg("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Res<Void>().code(500).msg("服务错误");
        }
    }
}
